package com.xr.blackhoole.mvc.interceptor;

import com.xr.blackhoole.mvc.context.BlackholeContext;
import com.xr.blackhoole.mvc.context.BlackholeContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

/**
 * 链路跟踪Request设置值
 */
public class MvcWormholeWebInterceptor implements WebRequestInterceptor {
    
    @Override
    public void preHandle(WebRequest webRequest) throws Exception {
        //失效上下文，解决Tomcat线程复用问题
        BlackholeContextHolder.invalidContext();
        String wormholeValue = webRequest.getHeader(BlackholeContextHolder.BLACKHOLE_REQUEST_MARK);
        if (StringUtils.isNotEmpty(wormholeValue)){
            BlackholeContextHolder.setContext(new BlackholeContext(wormholeValue));
        }

    }

    @Override
    public void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {

    }

    @Override
    public void afterCompletion(WebRequest webRequest, Exception e) throws Exception {

    }
}
